﻿using System;
using System.Security;
using System.Threading;
using System.Windows.Forms;

using Brilliance;
using Brilliance.navigation;

using log4net;

namespace SampleApplication
{
    internal static class Program
    {
        private static readonly ILog log;
        private static INavigator navigator;

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        private static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
            if (OneClick.Check(args))
            {
                Run();
            }
            else
            {
                MessageBox.Show(OneClick.Message);
            }
        }

        private static void Run()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.ThreadException += Application_ThreadException;
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            IContainer container = new Container();
            IRegistry registry = new Registry(container);

            navigator = new Navigator(new ViewFactory(), new PresenterFactory(registry));
            navigator.Start(new WelcomeWindowAction());
            Application.Run();
        }

        private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            if (e.Exception is SecurityException)
            {
                log.Info(e.Exception.ToString());
            }
            else
            {
                log.Fatal(e.Exception.ToString());
            }
        }

        private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            if (navigator != null)
            {
                log.Fatal(e.ExceptionObject.ToString());
            }
            else
            {
                Environment.Exit(1);
            }
        }
    }
}